const app = getApp();
var address = require('./address.json')
let windowWidth = 0,scrollTimer = false, tabBar
Component({
  mixins: [],
  ref() {
      return { 
		show: () => this.show()
	  }
},
  data: {
    // config: app.config,
	name: "gk-city",
	isFirst: true,
	rightIcon:true,
	scrollLeft: 500, //顶部选项卡左滑距离
	scrollTop:0,
	enableScroll: true,
	tabCurrentIndex: 0, //当前选项卡索引
	// tabbars: this.provincedata,
	tabbars: [],
	showData:address,
	showPicker: false
  },
  props: {
	  headtitle: {    // 使用多少个tab
	    type: String,
	    default: ""
	  },
	  pickerSize: {    // 使用多少个tab
	    type: [String, Number],
	    default: 1
	  },
	  // 默认的省市区id，如果不使用id的情况下则为[]；
	  data: address,
	  provincedata: [],
	  onFuncvalue:(data) => console.log(data),
  },
  didMount() {
	  this.setData({
		  tabbars: this.props.provincedata
	  })
	  // console.log(this.data.tabbars)
  },
  didUpdate() {},
  didUnmount() {},
  methods: {
	  show(){
		this.setData({
			showPicker: true
		})
		const provincedata = this.props.provincedata
		const pickerSize = this.props.pickerSize
	    windowWidth = my.getSystemInfoSync().windowWidth
	    if(provincedata && provincedata.length>0&&provincedata.length<pickerSize&&this.data.isFirst&&provincedata[provincedata.length-1].value!=""){
	      // this.data.showData=this.findSameId(this.props.data,this.data.tabbars[provincedata.length],this.data.tabbars[provincedata.length-1])
	      this.setData({
	      	showData: this.findSameId(this.props.data,this.data.tabbars[provincedata.length],this.data.tabbars[provincedata.length-1])
	      })
		  var current={
	        text:"请选择",
	        value:"",
	      }
		  var copyData = [...this.data.tabbars]
		  copyData.push(current)
		  this.setData({
			  tabbars: copyData,
			  tabCurrentIndex: provincedata && provincedata.length-1,
			  scrollTop: 0
		  })
		  console.log(this.props.data, 'if')
	      // this.data.tabbars.push(current)
	      // this.data.tabCurrentIndex=provincedata && provincedata.length-1
	      // this.data.scrollTop=0
	      this.setScroll(this.data.tabCurrentIndex)
	    }else{
	      // this.data.showData=this.findSameId(this.props.data,this.data.tabbars[provincedata && provincedata.length-1],this.data.tabbars[provincedata && provincedata.length-2])
	      // this.$nextTick(()=>{
	      //   this.data.tabCurrentIndex=provincedata && provincedata.length-1
	      //   this.data.scrollTop=0
	      //   this.setScroll(this.data.tabCurrentIndex)
	      // })
		  this.setData({
		  	showData: this.findSameId(this.props.data,this.data.tabbars[provincedata && provincedata.length-1],this.data.tabbars[provincedata && provincedata.length-2]),
			tabCurrentIndex: provincedata && provincedata.length-1,
			scrollTop: 0,
		  })
		  // console.log(this.props.provincedata)
		  console.log(this.props.data, 'else')
		  this.setScroll(this.data.tabCurrentIndex)
	    }
	  },
	  findSameId(tree, currentTab,preTab) {
	    let retNode = null
	    function deepSearch(tree, currentTab,preTab) {
	      for (var i = 0; i < tree.length; i++) {
	        if (tree[i].children && tree[i].children.length > 0) {
	          deepSearch(tree[i].children, currentTab,preTab)
	        }
	        var flag=currentTab==undefined?true:(currentTab.value===""?true:false)
	        var value=tree[i].value+""
	        var text=tree[i].text
	        if (preTab!=null&&flag&&preTab.text=== text&&preTab.value+"" ===value) {
	          retNode=tree[i].children
	          break
	        }else if (currentTab!=null&&currentTab.text=== text&&currentTab.value+"" === value) {
	          retNode=tree
	          break
	        }
	      }
	    }
	    deepSearch(tree, currentTab,preTab)
	    return retNode==null?tree:retNode
	  },
	  		
	  hide(){
	    // this.showPicker = false
		this.setData({
			showPicker: false
		})
	  },
	  //tab切换
	  changeTab(e){
	    let index = e.target.dataset.index
	    this.setScroll(index)
	    //延迟300ms,等待swiper动画结束再修改tabbar
	    // this.tabCurrentIndex = index 
	    // this.showData=this.findSameId(this.data,this.tabbars[index],index===0?this.tabbars[index]:this.tabbars[index-1])
	    this.setData({
			tabCurrentIndex: index,
			showData:this.findSameId(this.props.data,this.data.tabbars[index],index===0?this.data.tabbars[index]:this.data.tabbars[index-1])
		})
		setTimeout(()=>{
	      this.getScroll("show"+index)
	    }, 10)
	  },
	  //获得元素的size
	  getElSize(id) { 
	    return new Promise((res, rej) => {
	      let el = my.createSelectorQuery().in(this).select("#" + id)
	      el.fields({
	        size: true,
	        scrollOffset: true,
	        rect: true
	      }, (data) => {
	        res(data)
	      }).exec()
	    })
	  },
	  
	  /**
	   * 修改地址的时候触发
	   * @param {number} index : 表示是省，还是市，还是区
	   * @param {number} item : 表示当前点击的对象
	   */
	  changCity(e) {
		  var index = this.data.tabCurrentIndex
		  var item = e.target.dataset.item
		  console.log(index, item, this.data.tabbars[index])
	    if (this.data.tabbars[index].value != item.value) {
	      const selectUIValue = { text: item.text, value: item.value }
	      // this.$set(this.tabbars, index, selectUIValue) // 设置所选中的值
		  // var copyData = [...this.data.tabbars]
		  // copyData[index] = selectUIValue
		  // this.setData({
			 //  tabbars: copyData
		  // })
	      this.setData({
			  ['tabbars['+index+']']: selectUIValue
		  })
	      // LOG: 说明这是在修改前面已选择好的省份或者城市
	      if (index < (this.data.tabbars.length - 1)) {
	        const newArr = [...this.data.tabbars]
	        newArr.splice(index + 1)
	        // this.tabbars = newArr
			this.setData({
				tabbars: newArr
			})
	      }
	  
	      if (this.data.tabbars.length < this.props.pickerSize) { // 说明地址还没有选择完全
	        const current={
	          text:"请选择",
	          value:""
	        } // 下一个地址（市或者区）的占位
	        // this.showData = item.children // 设置下一个地址选择的显示数据（比如说城市列表，区的列表）
	        this.setData({
				showData: item.children
			})
	        // LOG: 直接push的话Vue监测不到data发生变化，将不会更新，详情参考：https://blog.csdn.net/a303944689/article/details/81393263
	        // this.tabbars.push(current)
	        const newTabBars = [...this.data.tabbars]
	        newTabBars.push(current)
	        // this.tabbars = newTabBars
			this.setData({
				tabbars: newTabBars,
				tabCurrentIndex: this.data.tabCurrentIndex+1,
				scrollTop: 0
			})
	        // this.tabCurrentIndex++ 
	        // this.scrollTop = 0
	        this.setScroll(index)
	      } else { // 表明地址已经选中完全了，通知上层UI组件
	        // this.$emit("funcvalue",this.tabbars)
			this.props.onFuncvalue(this.data.tabbars)
			// console.log(this.props.onFuncvalue)
	        this.hide()
	      }
	    }
	  },
	  
	  async setScroll(index){
	    let width = 0
	    let nowWidth = 0
	    for (let i = 0; i <= index; i++) {
	      let result = await this.getElSize("tab" + i)
	      width += result.width
	      if(i === index){
	        nowWidth = result.width
	      }
	    }
	    if ((width+nowWidth)>windowWidth) {
	      this.scrollLeft=width+nowWidth
	    }else{
	      this.scrollLeft = 0
	    } 
	  },
	  getScroll(id) {
	    my.createSelectorQuery().in(this).select(".panel-scroll-box").boundingClientRect((data)=>{
	      my.createSelectorQuery().in(this).select("#" + id).boundingClientRect((res)=>{
	        if(res != undefined && res != null && res != ""){
	          // this.scrollTop=res.top-data.top
			  this.setData({
				  scrollTop: res.top-data.top
			  })
	        }
	      }).exec()
	    }).exec()
	  }
  },
});